<template>
  <el-dialog :title="title" :visible.sync="visible">
    <el-tree
      class="filter-tree"
      :data="authTree"
      :default-checked-keys="filterLeafNode(checkedKeys)"
      node-key="id"
      highlight-current
      show-checkbox
      ref="menuTree"
      default-expand-all>
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="updatePermession">更 新</el-button>
    </div>
  </el-dialog>
</template>


<script>
// key: 子节点id
// value: 父节点id
let authMap = {}
export default {
  props: ['authTree', 'checkedKeys'],
  data () {
    return {
      title: '权限分配',
      visible: false
    }
  },
  methods: {
    updatePermession () {
      const ids = this.$refs.menuTree.getCheckedKeys()
      const harfIds = this.$refs.menuTree.getHalfCheckedKeys()
      this.$emit('updateMenuId', [...ids, ...harfIds])
    },
    showAuthDialog () {
      this.visible = true
    },
    hideAuthDialog () {
      this.visible = false
    },
    thumpedTree (arr, parentId) {
      if (!Array.isArray(arr) || !arr.length) return
      arr.forEach(item => {
        authMap[item.id] = parentId
        this.thumpedTree(item.children, item.id)
      })
    },
    filterLeafNode (nodeIds) {
      const idMap = nodeIds.reduce((map, item) => ((map[item] = true) && map), {})
      nodeIds.forEach(id => {
        const parentId = authMap[id]
        if (parentId in idMap) {
          idMap[parentId] = false
        }
      })
      return Object.entries(idMap).filter(item => item[1]).map(item => item[0])
    }
  },
  watch: {
    checkedKeys (nval) {
      if (this.rendered) {
        const checkedKeys = this.filterLeafNode(nval)
        this.$refs.menuTree.setCheckedKeys(checkedKeys)
      } else {
        this.rendered = true
      }
    },
    authTree (nval) {
      if (Array.isArray(nval)) {
        authMap = {}
        this.thumpedTree(nval, -1)
      }
    }
  }
}
</script>


<style scoped>

</style>
